<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="就诊卡号" prop="cardId">
        <el-input
          v-model="queryParams.cardId"
          placeholder="请输入就诊卡号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="交易类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择交易类型"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option label="缴费" value="缴费" />
          <el-option label="退费" value="退费" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreatetime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['index']"
          >缴费</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleRefund"
          v-hasPermi="['index']"
          >退费</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="payList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="就诊卡号" align="center" prop="cardId" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="余额" align="center" prop="money" />
      <el-table-column label="缴费金额" align="center" prop="addfee" />
      <el-table-column label="退费金额" align="center" prop="tuifee" />
      <el-table-column label="类型" align="center" prop="type" />
      <el-table-column label="缴费渠道" align="center" prop="qudao" />
      <el-table-column label="缴费状态" align="center" prop="status" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createtime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createtime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加缴费信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="payRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="就诊卡号" prop="cardId">
          <el-input
            v-model="form.cardId"
            placeholder="请输入就诊卡号"
            @blur="fetchPatientName"
          />
        </el-form-item>
        <el-form-item label="患者姓名" prop="patientName">
          <el-input
            v-model="form.patientName"
            placeholder="请输入患者姓名"
            readonly
          />
        </el-form-item>
        <el-form-item label="余额" prop="money">
          <el-input v-model="form.money" placeholder="就诊卡余额" readonly />
        </el-form-item>
        <el-form-item label="缴费金额" prop="addfee">
          <el-input v-model="form.addfee" placeholder="请输入缴费金额" />
          <!-- 添加快捷金额按钮 -->
          <div class="quick-amounts">
            <el-button
              v-for="amount in quickAmounts"
              :key="amount"
              @click="handleQuickAmount(amount)"
              size="small"
            >
              {{ amount }}元
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="支付方式" prop="qudao">
          <el-select v-model="form.qudao" placeholder="请选择支付方式">
            <el-option label="现金支付" value="现金支付" />
            <el-option label="支付宝支付" value="支付宝支付" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 退费信息对话框 -->
    <el-dialog
      title="退费"
      v-model="refundOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="refundRef"
        :model="form"
        :rules="refundRules"
        label-width="80px"
      >
        <el-form-item label="就诊卡号" prop="cardId">
          <el-input
            v-model="form.cardId"
            placeholder="请输入就诊卡号"
            @blur="fetchPatientName"
          />
        </el-form-item>
        <el-form-item label="患者姓名" prop="patientName">
          <el-input
            v-model="form.patientName"
            placeholder="请输入患者姓名"
            readonly
          />
        </el-form-item>
        <el-form-item label="余额" prop="money">
          <el-input v-model="form.money" placeholder="就诊卡余额" readonly />
        </el-form-item>
        <el-form-item label="退费金额" prop="tuifee">
          <el-input v-model="form.tuifee" placeholder="请输入退费金额" />
        </el-form-item>
        <!-- <el-form-item label="支付方式" prop="qudao">
          <el-select v-model="form.qudao" placeholder="请选择支付方式">
            <el-option label="现金支付" value="现金支付" />
            <el-option label="微信支付" value="微信支付" />
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRefund">确 定</el-button>
          <el-button @click="cancelRefund">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Pay">
import { listPay, refund, addPay } from "@/api/fee/pay";
import { getPatientNameByCardId } from "@/api/patients/patientlist";

const { proxy } = getCurrentInstance();

const payList = ref([]);
const open = ref(false);
const refundOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreatetime = ref([]);

const data = reactive({
  form: {
    cardId: null,
    patientName: null,
    money: 0.0, // 初始值为浮点数
    addfee: 0.0, // 初始值为浮点数
    qudao: null,
  },
  // form: {
  //   tuifee: 0.0, // 初始值为浮点数
  //   qudao: null,
  // },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cardId: null,
    patientName: null,
    type: null,
    qudao: null,
    createtime: null,
  },
  rules: {
    qudao: [{ required: true, message: "请选择支付方式", trigger: "change" }],
  },
  refundRules: {
    tuifee: [{ required: true, message: "请输入退费金额", trigger: "blur" }],
    qudao: [{ required: true, message: "请选择支付方式", trigger: "change" }],
  },
});

const { queryParams, form, rules, refundRules } = toRefs(data);

/** 根据就诊卡号查询病人姓名 */
const fetchPatientName = async () => {
  if (form.value.cardId) {
    try {
      const response = await getPatientNameByCardId(form.value.cardId);
      if (response.patientName) {
        form.value.patientName = response.patientName;
        form.value.patientId = response.patientsId;
        form.value.money = response.money;
      } else {
        proxy.$modal.msgWarning("该卡号不存在");
      }
    } catch (error) {
      proxy.$modal.msgError("系统异常");
    }
  }
};

// 快捷选择缴费金额
// 在setup()中添加：
const quickAmounts = ref([50, 100, 200, 500, 1000]);

const handleQuickAmount = (amount) => {
  form.value.addfee = amount;
};

/** 查询缴费信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreatetime && "" != daterangeCreatetime) {
    queryParams.value.params["beginCreatetime"] = daterangeCreatetime.value[0];
    queryParams.value.params["endCreatetime"] = daterangeCreatetime.value[1];
  }
  listPay(queryParams.value).then((response) => {
    payList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 退费取消按钮
function cancelRefund() {
  refundOpen.value = false;
  resetRefund();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    cardId: null,
    patientId: null,
    patientName: null,
    money: 0.0,
    addfee: 0.0,
    tuifee: null,
    type: null,
    qudao: null,
    createtime: null,
  };
  proxy.resetForm("payRef");
}

// 退费表单重置
function resetRefund() {
  form.value = {
    id: null,
    cardId: null,
    patientId: null,
    patientName: null,
    money: 0.0,
    addfee: 0.0,
    tuifee: null,
    type: null,
    qudao: null,
    createtime: null,
  };
  proxy.resetForm("refundRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreatetime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "缴费";
}

/** 退费按钮操作 */
function handleRefund(row) {
  resetRefund();
  refundOpen.value = true;
  title.value = "添加退费信息";
}

// 新增支付宝支付方法
const payByAlipay = (tradeNo, totalAmount) => {
  const returnUrl = encodeURIComponent(
    "http://127.0.0.1:80/fee/pay" // 调整为你的实际返回地址
  );
  window.location.href = `http://127.0.0.1:8080/alipay/pay?totalAmount=${totalAmount}&returnUrl=${returnUrl}&tradeNo=${tradeNo}`;
};

/** 提交新增或修改缴费信息 */
function submitForm() {
  proxy.$refs["payRef"].validate((valid) => {
    if (valid) {
      addPay(form.value)
        .then((response) => {
          console.log("response:", response);
          if (form.value.qudao === "支付宝支付") {
            // 调用支付宝支付（假设接口返回tradeNo）
            payByAlipay(response.data, form.value.addfee);
          } else {
            proxy.$modal.msgSuccess("操作成功");
            open.value = false;
            getList();
          }
        })
        .catch((error) => {
          proxy.$modal.msgError(error.message || "操作失败");
        });
    }
  });
}

/** 提交退费信息 */
function submitRefund() {
  proxy.$refs["refundRef"].validate((valid) => {
    refund(form.value).then((response) => {
      proxy.$modal.msgSuccess("退费成功");
      refundOpen.value = false;
      getList();
    });
  });
}

getList();
</script>

<style scoped>
.el-form-item {
  margin-bottom: 10px;
}

.quick-amounts {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.quick-amounts .el-button {
  padding: 6px 12px;
}
</style>
